from SPARQLWrapper import SPARQLWrapper, JSON, N3
from rdflib.graph import Graph, ConjunctiveGraph


DBPEDIA_ENDPOINT = "http://dbpedia.org/sparql"

prefixes = {
    'rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    'rdfs': "http://www.w3.org/2000/01/rdf-schema#",
    'owl': "http://www.w3.org/2002/07/owl#",
    'xsd': "http://www.w3.org/2001/XMLSchema#",
    'skos': "http://www.w3.org/2004/02/skos/core#",

    'dc': "http://purl.org/dc/elements/1.1/",
    'dct': "http://purl.org/dc/terms/",
    'foaf': "http://xmlns.com/foaf/0.1/",

    'dbpedia': "http://dbpedia.org/",
    'dbpprop': "http://dbpedia.org/property/",
    'dbpowl': "http://dbpedia.org/ontology/",
}

sparql_prefixes = "\n".join("PREFIX %s: <%s>"%kv for kv in prefixes.items())

query_body = sparql_prefixes + """

CONSTRUCT {

    ?country
        %(parts)s
        .

} WHERE {

    ?country
        a dbpowl:Country;
        dbpowl:governmenttype ?govtype;
        rdfs:label ?label .

    OPTIONAL {
        ?country
            dbpprop:populationCensus ?populationCensus;
            dbpprop:populationCensusYear ?populationCensusYear .
    }
    OPTIONAL {
        ?country
            dbpprop:populationEstimate ?populationEstimate;
            dbpprop:populationEstimateYear ?populationEstimateYear .
    }

    OPTIONAL { ?country dbpprop:yearEnd ?yearEnd }
    FILTER( !BOUND(?yearEnd) )
    FILTER( %(langmatch)s )
}
"""

parts = [
    "a dbpowl:Country",
    "dbpowl:governmenttype ?govtype",
    "dbpprop:populationCensus ?populationCensus",
    "dbpprop:populationCensusYear ?populationCensusYear",
    "dbpprop:populationEstimate ?populationEstimate",
    "dbpprop:populationEstimateYear ?populationEstimateYear",
    "rdfs:label ?label",
]


def queries_to_graph(endpoint, langs):
    graph = ConjunctiveGraph()
    langmatch = " || ".join("LANG(?label) = '%s'" % l for l in langs)
    for pfx, uri in prefixes.items():
        graph.bind(pfx, uri)
    for part in parts:
        query = query_body % dict(
                parts=part,
                langmatch=langmatch)
        graph += do_query(endpoint, query)
    print graph.serialize(format='n3')

def do_query(endpoint, query):
    wrapper = SPARQLWrapper(DBPEDIA_ENDPOINT)
    wrapper.setQuery(query)
    return wrapper.queryAndConvert()


if __name__ == '__main__':

    langs = ['en', 'sv']
    queries_to_graph(DBPEDIA_ENDPOINT, langs)

